<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="../../org/angular.min.js"></script>
</head>

<body ng-app="app">
    <!-- 控制器一 -->
    <div ng-controller="ctrl">
        <table width="500" border="1">
            <tr>
                <th>网站</th>
                <th>url</th>
            </tr>
            <tr ng-repeat="d in data.webs">
                <td>{{d.title}}</td>
                <td>{{d.url}}</td>
            </tr>
        </table>
        <button ng-click="removeAll()">删除所有</button>
    </div>


    <hr />
    <!-- 控制器二 -->
    <table width="500" border="1" ng-controller="ctrl2">
        <tr>
            <th>网站</th>
            <th>url</th>
        </tr>
        <tr ng-repeat="a in one">
            <td>{{a.title}}</td>
            <td>{{a.url}}</td>
        </tr>
    </table>


    <script>
        var m = angular.module('app', []);
        //创建一个获取数据的服务
        m.factory('webService', ['$http', function($http) {
            var obj = {
                data: {
                    webs: []
                },
                all: function() {
                    return $http.get('1.php', {
                        cache: true
                    }).then(function(res) {
                        obj.data.webs = res.data;
                        return obj.data;
                    });
                },
                find: function(id) {
                    return this.all().then(function(data) {
                        for (var i = 0; i < data.webs.length; i++) {
                            if (data.webs[i].id === id) {
                                return data.webs[i];
                            }
                        }
                    })
                },
                flush: function() {
                    obj.data.webs = [];
                }
            }
            return obj;
        }])
        m.controller('ctrl', ['$scope', 'webService', function($scope, webService) {
            webService.all().then(function(data) {
                $scope.data = data;
            })
            $scope.removeAll = function() {
                webService.flush();
            }
        }])

        m.controller('ctrl2', ['$scope', 'webService', function($scope, webService) {
            webService.find(1).then(function(data) {
                console.log(data);
                $scope.one = [data];
            });
        }])
    </script>
</body>

</html>
